package com.hxzy.tms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.tms.Assert;
import com.hxzy.tms.SessionHolder;
import com.hxzy.tms.dao.TeamDao;
import com.hxzy.tms.dao.TeamUserDao;
import com.hxzy.tms.dao.UserDao;
import com.hxzy.tms.dao.BaseDao.Params;
import com.hxzy.tms.entity.Team;
import com.hxzy.tms.entity.TeamUser;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.service.ServiceResult;
import com.hxzy.tms.service.TeamService;
/**
 * 团队Service实现类
 * @author team1
 *
 */
public class DefaultTeamService implements TeamService {
	private TeamDao teamDao;
	private UserDao userDao;
	private TeamUserDao teamUserDao;
	
	public ServiceResult<Team> read(long id) {
  	    Team team = teamDao.read(Team.class, id);
        return new ServiceResult<Team>(1, team);
	}
	
	public ServiceResult<Team> read(String domain) {
  	    List<Team> teams = teamDao.read("from Team where subdomain = :subdomain", new Params("subdomain", domain));
        return new ServiceResult<Team>(1, teams.isEmpty() ? null : teams.get(0));
	}
	
	public ServiceResult<Team> create(String name, String desc, String intro, String subdomain, Date gmtBegin,
			Date gmtEnd,Integer status) {
		Assert.notBlank(name, "团队名字不能为空");
		Assert.notBlank(desc, "团队描述不能为空");
		Assert.notBlank(intro, "团队介绍不能为空");
		Assert.notEmpty(subdomain, "域名不能为空");
		Assert.notEmpty(gmtBegin, "开始日期不能为空");
		Assert.notEmpty(gmtEnd, "结束日期不能为空"); 
		Assert.notEmpty(SessionHolder.get(), "必须是登陆用户才能创建团队");
		return saveOrUpdate(null, name, desc, intro, subdomain, gmtBegin, gmtEnd,1);
	}
	
	private  ServiceResult<Team> saveOrUpdate(Long id,String name, String desc, String intro, String subdomain, Date gmtBegin,
			Date gmtEnd,Integer status){
		
        if (gmtEnd.getTime() <= gmtBegin.getTime()) {
            return new ServiceResult<Team>(-1, null, "开始时间必须早于预计结束时间");
        }

        if (!(subdomain.charAt(0) >= 'a' && subdomain.charAt(0) <= 'z')) {
            return new ServiceResult<Team>(-2, null, "团队二级域名首字母必须是小写字母 a-z");
        }

        List<Team> teams = new ArrayList<Team>();
        if (id != null) {
            teams = teamDao.read("from Team where name = :name and id != :id", new Params("name", name),
                    new Params("id", id));
        } else {
            teams = teamDao.read("from Team where name = :name", new Params("name", name));
        }
        if (!teams.isEmpty()) {
            return new ServiceResult<Team>(-3, null, "团队名字重复");
        }

        if (id != null) {
            teams = teamDao.read("from Team where subdomain = :subdomain and id != :id",
                    new Params("subdomain", subdomain), new Params("id", id));
        } else {
            teams = teamDao.read("from Team where subdomain = :subdomain", new Params("subdomain", subdomain));
        }
        if (!teams.isEmpty()) {
            return new ServiceResult<Team>(-4, null, "团队个性域名重复");
        }
//		Team team =( teamDao.read(Team.class, id) != null ) ? teamDao.read(Team.class, id) : new Team();
		Team team = new Team();
		team.setName(name);
		team.setDesc(desc);
		team.setIntro(intro);
		team.setStatus(1);
		team.setSubdomain(subdomain);
		team.setUserCreate(SessionHolder.get());
		team.setGmtModified(0L);
		team.setGmtBegin(gmtBegin.getTime()/1000);
		team.setGmtEnd(gmtEnd.getTime()/1000);
		 if (id == null) {
	            team.setUserCount(0L);
	        }

	        if (id != null) {
	            team.setId(id);
	            teamDao.update(team);
	        } else {
	            teamDao.create(team);
	        }
		return new ServiceResult<Team>(1,team);
		
	}
	
	public ServiceResult<Team> update(long id, String name, String desc, String intro, String subdomain, Date gmtBegin,
			Date gmtEnd,Integer status) {
	  Assert.greaterThan(id, 0L, "id 必须大于 0");
      Assert.notBlank(name, "name 不能为空");
      Assert.notBlank(desc, "desc 不能为空");
      Assert.notBlank(subdomain, "subdomain 不能为空");
      Assert.notEmpty(gmtBegin, "开始时间不能为空");
      Assert.notEmpty(gmtEnd, "结束时间不能为空");
      Assert.notEmpty(SessionHolder.get(), "必须是登录用户才能创建团队");

      if (teamDao.read(Team.class, id) != null
              && !teamDao.read(Team.class, id).getUserCreate().getId().equals(SessionHolder.get().getId())) {
          return new ServiceResult<Team>(-5, null, "只能编辑自己的团队");
      }
      return saveOrUpdate(id, name, desc, intro, subdomain, gmtBegin, gmtEnd,1);
	}
	
	/**
	 * 团队的邀请功能 
	 */
	public int invite(long uid, long teamId, String email) {
		//验证参数
	    if (uid <= 0) {
          throw new IllegalArgumentException("uid 不能小于0");
        }
	    if (teamId <= 0 ) {
          throw new IllegalArgumentException("teamId 不能小于 0 ");
        }
	    if (StringUtils.isBlank(email)) {
          throw new IllegalArgumentException("邮箱不能为空");
        }
	    // 数据逻辑的检查
	    Team team = null;
	    team = teamDao.read(Team.class, teamId);
	    if (! team.getUserCreate().getId().equals(uid)) {
          return -1;
        }
	    Map<String, Object> param = new HashMap<String, Object>();
	    param.put("email", email);
	    List<User> inviteUsers = userDao.read("from User where email = :email", param);
	    if (inviteUsers.isEmpty()) {
           return -2;
        }
	    User inviteUser = inviteUsers.get(0);
	    if (inviteUser.getId().equals(SessionHolder.get().getId())) {
            return -3;//不能邀请自己
        }
	    
		Map<String, Object> param2 = new HashMap<String, Object>();
		param2.put("user_id", inviteUser.getId());
		param2.put("team_id", teamId);
		List<TeamUser> teamUsers = teamUserDao.read("from TeamUser where user.id = :user_id and team.id = :team_id", param2);
		if (teamUsers.isEmpty()) {
            return -4;//用户已经加入
        }
		
		TeamUser teamUser = new TeamUser();
		teamUser.setUser(inviteUser);
		teamUser.setTeam(team);
        teamUser.setUserNickname(inviteUser.getNickname());
        teamUser.setStatus(1);
        teamUser.setUidCreate(uid);
        teamUser.setUidModified(null);
        teamUser.setGmtCreate(System.currentTimeMillis() / 1000);
        teamUser.setGmtModified(0L);
        
        teamUserDao.create(teamUser);
        team = teamDao.read(Team.class, teamId);
        team.setUserCount(team.getUserCount() + 1);
        teamDao.update(team);
		return 1;
	}
	
	public ServiceResult<ArrayList<Team>> teamLists(Integer status) {
	    if (SessionHolder.get() == null) {
            return new ServiceResult<ArrayList<Team>>(-1, null, "用户未登录");
        }
	    List<Params> params = new ArrayList<Params>();
        String sql = "from Team where userCreate.id = :user_id";
        params.add(new Params("user_id", SessionHolder.get().getId()));
        if (status != null) {
            sql += " and status = :status";
            params.add(new Params("status", status));
        }

        sql += " order by gmtCreate desc";

        List<Team> teamList = teamDao.read(sql, params);

//        return new ServiceResult<ArrayList<Team>>(1, teamList);
          return null;
	}

	
	public TeamDao getTeamDao() {
		return teamDao;
	}

	public void setTeamDao(TeamDao teamDao) {
		this.teamDao = teamDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

  public TeamUserDao getTeamUserDao() {
    return teamUserDao;
  }

  public void setTeamUserDao(TeamUserDao teamUserDao) {
    this.teamUserDao = teamUserDao;
  }

	
	
    
}